package com.ruoyi.quartz.task;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.bizsys.service.ILoanIouService;
import com.ruoyi.bizsys.vo.LoanIouVo;
import com.ruoyi.market.config.MarketUserConfig;
import com.ruoyi.market.util.HttpConnetUtil;
import com.ruoyi.system.mapper.SysDictDataMapper;
import com.ruoyi.system.service.ISysDictDataService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.text.SimpleDateFormat;
import java.util.List;

/**
 * @Author: ygw
 * @Date: 2022/05/05/11:58
 * @Description:
 */
@Slf4j
@Component("loanIouTask")
public class LoanIouTask {

    @Autowired
    private ILoanIouService loanIouService;

    @Autowired
    MarketUserConfig marketUserConfig;

    @Autowired
    ISysDictDataService sysDictDataService;

    private static final String IOU_INTERVAL_HOURS = "iou_intervalHours";

    //定时查询生成的IOU订单
    public void loanIouTask(){
        log.info("开始执行loanIouTask定时任务");
        //查询近以下是生成的iou订单
        List<LoanIouVo> loanIouVoList = loanIouService.selectIouTask(sysDictDataService.selectDictValue(IOU_INTERVAL_HOURS));
        JSONObject jsonParam = marketUserFormatt(loanIouVoList);
        //推送至营销系统
        if(jsonParam.getJSONArray("data").size()>0){
            String resultInfo = null;
            try {
                resultInfo = HttpConnetUtil.sendPost(marketUserConfig.getMarketIouImportUrl(), jsonParam.toJSONString());
            } catch (Exception e) {
                log.error("--------- 推送至营销系统 异常",e);
            }
            log.info("-------- 成功推送至 营销系统： " + resultInfo);
        }
    }

    public JSONObject marketUserFormatt(List<LoanIouVo> loanIouVoList){
        JSONObject jsonParam = new JSONObject();
        JSONArray jsonArray = new JSONArray();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for(LoanIouVo loanIouVo : loanIouVoList){
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("loanAmt",loanIouVo.getLoanAmt());
            jsonObject.put("phone",loanIouVo.getPhone());
            jsonObject.put("loanSerialNo",loanIouVo.getLoanSerialNo());
            jsonObject.put("custNo",loanIouVo.getCustNo());
            jsonObject.put("createTime",sdf.format(loanIouVo.getCreateTime()));
            jsonObject.put("userUuid",loanIouVo.getUserUuid());
            jsonObject.put("userName",loanIouVo.getUserName());
            jsonObject.put("orderCreateTime", sdf.format(loanIouVo.getOrderCreateTime()));
            jsonArray.add(jsonObject);
        }
        jsonParam.put("data",jsonArray);
        return jsonParam;
    }
}

